package com.lzh.crm.service.impl;
import java.util.List;
import java.util.stream.Collectors;

import com.lzh.crm.mapper.UserMapper;
import com.lzh.crm.pojo.User;
import com.lzh.crm.service.UserService;
import com.lzh.crm.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUserName(String uName) {
        User u = userMapper.findByUserName(uName);
        return u;
    }

    @Override
    public void register(User user) {
        //加密
        String md5String = Md5Util.getMD5String(user.getPassword());
        user.setPassword(md5String);
        //添加
        userMapper.insert(user);
    }

    @Override
    public void insert(User user) {
        //加密
        String md5String = Md5Util.getMD5String(user.getPassword());
        user.setPassword(md5String);
        userMapper.insert(user);
    }

    public void delete(Integer userId) {
        userMapper.delete(userId);
    }

    @Override
    public void update(User user) {
        if (user.getPassword() != null) {
            String md5String = Md5Util.getMD5String(user.getPassword());
            user.setPassword(md5String);
        }
        userMapper.update(user);
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Override
    public List<User> selectNeed(User user) {
        return userMapper.selectNeed(user);
    }

    @Override
    public List<User> convertExcelDTOToUser(List<User> dtoList) {
        return dtoList.stream().map(dto -> {
            User user = new User();
            user.setUserName(dto.getUserName());
            user.setPassword(Md5Util.getMD5String(dto.getPassword()));
            user.setRealName(dto.getRealName());
            user.setAddress(dto.getAddress());
            user.setPhone(dto.getPhone());
            user.setSex(dto.getSex());
            user.setAge(dto.getAge());
            return user;
        }).collect(Collectors.toList());  //把Stream里的元素收集起来，转成一个新的 List 列表
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<User> userList) {
        userMapper.saveBatch(userList);
    }

    @Override
    public List<User> select() {
        return userMapper.select();
    }

}
